import axios from 'axios'
import type { AxiosInstance, AxiosRequestConfig, AxiosResponse } from 'axios'
import { Message } from '@arco-design/web-vue'

// 后端API基础URL
const API_BASE_URL = 'http://localhost:8000'

// 服务前缀映射
export const ServicePrefix = {
  USER: `${API_BASE_URL}/kyusers`,
  MERCHANT: `${API_BASE_URL}/kymerchants`,
  DISH: `${API_BASE_URL}/kydishes`,
  ORDER: `${API_BASE_URL}/kyorders`
}

// 创建axios实例
const createService = (baseURL: string): AxiosInstance => {
  const service = axios.create({
    baseURL,
    timeout: 10000
  })

  // 请求拦截器
  service.interceptors.request.use(
    (config) => {
      // 根据不同的服务选择不同的token
      let token;
      
      if (config.baseURL?.includes('/kymerchants')) {
        token = localStorage.getItem('merchant_token')
      } else if (config.baseURL?.includes('/kyusers')) {
        token = localStorage.getItem('token')
      } else {
        // 对于其他服务，尝试获取商家token或用户token
        token = localStorage.getItem('merchant_token') || localStorage.getItem('token')
      }
      
      if (token) {
        config.headers['Authorization'] = `Bearer ${token}`
      }
      return config
    },
    (error) => {
      return Promise.reject(error)
    }
  )

  // 响应拦截器
  service.interceptors.response.use(
    (response: AxiosResponse) => {
      // 直接返回响应数据，不做额外处理
      return response.data
    },
    (error) => {
      // 处理错误响应
      if (error.response) {
        const { status, data, config } = error.response
        
        if (status === 401) {
          // 根据请求的baseURL清除对应的token
          if (config.baseURL?.includes('/kymerchants')) {
            localStorage.removeItem('merchant_token')
            Message.error('商家登录已过期，请重新登录')
          } else if (config.baseURL?.includes('/kyusers')) {
            localStorage.removeItem('token')
            Message.error('用户登录已过期，请重新登录')
          } else {
            // 两个token都清除
            localStorage.removeItem('token')
            localStorage.removeItem('merchant_token')
            Message.error('登录已过期，请重新登录')
          }
        } else if (status === 403) {
          Message.error('没有权限访问该资源')
        } else if (status === 404) {
          Message.error('请求的资源不存在')
        } else if (status === 500) {
          Message.error('服务器内部错误')
        } else {
          Message.error(data?.message || '请求失败')
        }
      } else {
        Message.error('网络错误，请检查您的网络连接')
      }
      
      return Promise.reject(error)
    }
  )

  return service
}

// 创建各服务的实例
export const userService = createService(ServicePrefix.USER)
export const merchantService = createService(ServicePrefix.MERCHANT)
export const dishService = createService(ServicePrefix.DISH)
export const orderService = createService(ServicePrefix.ORDER)

// 封装GET请求
export function get<T>(service: AxiosInstance, url: string, params?: object): Promise<T> {
  return service.get(url, { params })
}

// 封装POST请求
export function post<T>(service: AxiosInstance, url: string, data?: object): Promise<T> {
  return service.post(url, data)
}

// 封装PUT请求
export function put<T>(service: AxiosInstance, url: string, data?: object): Promise<T> {
  return service.put(url, data)
}

// 封装DELETE请求
export function del<T>(service: AxiosInstance, url: string): Promise<T> {
  return service.delete(url)
} 